package com.wutianyi.maven.main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Map.Entry;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.wutianyi.maven.properties.ConfigProperties;
import com.wutianyi.maven.xml.ParserXmlDom4j;

public class Main {
	public static void main(String[] args) {
		ConfigProperties properties = new ConfigProperties();
		ParserXmlDom4j config = new ParserXmlDom4j();
		
		VelocityEngine engine = new VelocityEngine();
		engine.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		VelocityContext context = new VelocityContext();
		for(Entry<String, String> entry : config.getProperties().entrySet()) {
			String key = entry.getKey();
			String defaultValue = entry.getValue();
				
			String value = properties.getProperties(key, defaultValue);
			context.put(key, value);
		}
		for(Entry<String,String> entry : config.getGeneratorFiles().entrySet()) {
			Template template = engine.getTemplate(entry.getKey());
			PrintWriter writer = null;
			try {
				writer = new PrintWriter(new FileOutputStream(new File(Main.class.getResource("/").getFile(), entry.getValue())));
				template.merge(context, writer);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				if(null != writer) {
					
					writer.close();
				}
			}
		}
		properties.close();
	}
}
